package cn.b.sky.admin.controller;

import cn.b.sky.admin.model.DWZResult;
import cn.b.sky.admin.model.SaUser;
import cn.b.sky.admin.security.ManagementAuthentication;
import cn.b.sky.admin.security.ManagementContextHolder;
import cn.b.sky.admin.security.context.ManagementContext;
import cn.b.sky.admin.service.SaUserService;
import cn.b.sky.admin.utils.EncryptAlgorithm;
import cn.b.sky.admin.utils.ManagementSecurity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;


@Controller
@RequestMapping("/management/*")
public class ManagementController extends BaseController {

  @Resource
  private SaUserService saUserService;
  
  @RequestMapping(value = "login", method = RequestMethod.GET)
  public String login(Model model, HttpSession session) {

    return "management_login";
  }
  
  @RequestMapping(value = "index")
  public String index(Model model, HttpSession session){
    
    model.addAttribute("userInfo", ManagementSecurity.getAuthentication(session));
    
    return "admin/index";
  }
  
  @RequestMapping(value = "doLogin", method = RequestMethod.POST)
  public String doLogin(Model model, String userCode, String password, HttpSession session)
      throws UnsupportedEncodingException {
   
    SaUser user = saUserService.getSaUserByUserCode(userCode);
    if(null != user && EncryptAlgorithm.hexMD5(password).equals(user.getPassword())) {
      ManagementAuthentication authentication = new ManagementAuthentication(user.getUserCode(), user);
      ManagementContextHolder.getContext().setAuthentication(authentication);
      session.setAttribute(ManagementContextHolder.MANAGEMENT_SECURITY_CONTEXT, ManagementContextHolder.getContext());
      return "redirect:/manage/management/index";
    }
    model.addAttribute("message", "用户名或密码错误！");
    return "management_login";
  }
  
  @RequestMapping(value = "logout", method = RequestMethod.GET)
  public String logout(Model model, HttpServletRequest request){
    //移除session
    request.getSession(false).removeAttribute(ManagementContextHolder.MANAGEMENT_SECURITY_CONTEXT);
    ManagementContext context = ManagementContextHolder.getContext();
    context.setAuthentication(null);
    ManagementContextHolder.clearContext();
    
    return "management_login";
  }
  
  @RequestMapping(value = "changePWD", method = RequestMethod.GET)
  public String changePWD(Model model) {

    return "admin/changepwd";
  }
  
  @RequestMapping("savePwd")
  @ResponseBody
  public DWZResult savePwd(Model model, String navTabId, SaUser user, HttpServletRequest request) {
    try {
      if (user == null) {
        return ajaxError("参数异常!");
      }
      SaUser u = saUserService.getSaUserByUserCode(ManagementSecurity.getCurrentUserCode());
      if (EncryptAlgorithm.hexMD5(user.getPassword()).equals(u.getPassword())) {
        if (user.getPassword().equals(user.getNewPassword())) {
          return ajaxError("新密码不能和旧密码一样!");
        }
        saUserService.updateUserPwd(ManagementSecurity.getCurrentUserCode(),
            EncryptAlgorithm.hexMD5(user.getNewPassword()));
        return dialogAjaxDone("操作成功", navTabId, null, null, null);
      } else {
        return ajaxError("旧密码输入不正确!");
      }
    } catch (Exception e) {
      LOGGER.error("{}", e);
      model.addAttribute("message", e.getMessage());
      return ajaxError("操作失败");
    }
  }
}
